using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

namespace Weazel.Microblaze.Elf
{
  public class ElfIdentification
  {
    #region Enumerations
    public enum Ei_Class
    {
      ElfClassNone,
      ElfClass32,
      ElfClass64
    }

    public enum Ei_Data
    {
      ElfDataNone,
      ElfData2Lsb,
      ElfData2Msb
    }
    #endregion

    #region Properties
    private Ei_Class ei_class;
    public Ei_Class Ei_class
    {
      get { return ei_class; }      
    }

    private Ei_Data ei_data;
    public Ei_Data Ei_data
    {
      get { return ei_data; }
    }

    private int ei_version;
    public int Ei_version
    {
      get { return ei_version; }     
    }

    #endregion

    public void Read(BinaryReader reader)
    {
      byte[] e_ident = reader.ReadBytes(16);

      // check that this is a proper ELF file
      bool isElfFile =
        e_ident[0] == 0x7f &&
        e_ident[1] == (byte)'E' &&
        e_ident[2] == (byte)'L' &&
        e_ident[3] == (byte)'F';

      if (!isElfFile)
        throw new Exception();

      this.ei_class =
        e_ident[4] == 1 ? Ei_Class.ElfClass32 :
        e_ident[4] == 2 ? Ei_Class.ElfClass64 :
        Ei_Class.ElfClassNone;

      this.ei_data =
        e_ident[5] == 1 ? Ei_Data.ElfData2Lsb :
        e_ident[5] == 2 ? Ei_Data.ElfData2Msb :
        Ei_Data.ElfDataNone;

      this.ei_version = (int)e_ident[6];

    }

    public override string ToString()
    {
      StringBuilder str = new StringBuilder();
      str.AppendFormat("EI_CLASS   : {0} \n", this.ei_class);
      str.AppendFormat("EI_DATA    : {0} \n", this.ei_data);
      str.AppendFormat("EI_VERSION : {0} \n", this.ei_version);

      return str.ToString();
    }
  }
}
